package com.example.application4.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.application4.R;
import com.example.application4.pojo.User;

import java.util.List;

public class UserAdapter extends ArrayAdapter<User> {

    private Context context;
    private List<User> userList;

    public UserAdapter(Context context, List<User> userList) {
        super(context, 0, userList);
        this.context = context;
        this.userList = userList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            // 如果 convertView 为空，创建新的视图
            convertView = LayoutInflater.from(context).inflate(R.layout.item_user, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.textViewName = convertView.findViewById(R.id.textViewName);
            viewHolder.textViewEmail = convertView.findViewById(R.id.textViewEmail);
            convertView.setTag(viewHolder); // 将 ViewHolder 存储在视图的 Tag 中
        } else {
            // 如果 convertView 不为空，复用已有视图
            viewHolder = (ViewHolder) convertView.getTag();
        }

        try {
            // 获取当前位置的 User 对象
            User user = userList.get(position);
            // 设置用户名和电子邮件
            viewHolder.textViewName.setText("用户名: " + user.getUsername());
            viewHolder.textViewEmail.setText("电子邮箱: " + user.getEmail());
        } catch (IndexOutOfBoundsException e) {
            Toast.makeText(context, "用户数据获取错误", Toast.LENGTH_SHORT).show();
        }

        return convertView;
    }

    private static class ViewHolder {
        TextView textViewName;
        TextView textViewEmail;
    }
}